package com.wxyzz.common.core.interceptor;


import com.wxyzz.common.core.annotation.NoLoginCheck;
import com.wxyzz.common.core.exception.CustmerException;
import com.wxyzz.common.core.utils.JwtUtils;
import com.wxyzz.common.core.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/10/28
 * @Solgne 从想做到能做
 * @Desc
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断哪些接口不需要拦截
        if (handler instanceof HandlerMethod) {
            // 将控制层的方法封装为 HandlerMethod 对象
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
            // 使用 @NoLoginCheck 注解的方法直接放行
            if (ret) {
                return true;
            }
        }

        // 通过 token 判断是否放行
        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            throw new CustmerException(500,"请重新登录...");
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object uid = claims.get("uid");
            // 将uid存入ThreadLocal
            UserUtils.setUid(Integer.valueOf(uid.toString()));
        } catch (Exception e) {
            throw new CustmerException(500,"请重新登录...");
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除数据
        UserUtils.removeUid();
    }
}
